package com.dtflys.easyel.transform;

import com.dtflys.easyel.ast.ASTConstant;
import com.dtflys.easyel.ast.ASTNode;
import com.dtflys.easyel.ast.ASTType;
import com.dtflys.easyel.compile.EasyElSource;
import org.antlr.v4.runtime.Token;


/**
 * @author gongjun[jun.gong@thebeastshop.com]
 * @since v1.0.0
 */
public class ConstantTransformer extends ExpressionTransformer {


    public ASTConstant transformName(String name, ASTNode node) {
        ASTConstant constant = new ASTConstant(name, ASTType.STRING);
        setPosition(constant, node, node);
        printNode(constant);
        return constant;
    }

    public ASTConstant transformName(Token token) {
        ASTConstant constant = new ASTConstant(token.getText(), ASTType.STRING);
        setPosition(constant, token);
        printNode(constant);
        return constant;
    }


    public ASTConstant transform(EasyElSource source, Object value, Token startToken, Token endToken) {
        ASTConstant constant = new ASTConstant(filterString(source, value), ASTType.fromJavaClass(value.getClass()));
        setPosition(constant, startToken, endToken);
        printNode(constant);
        return constant;
    }


    public Object filterString(EasyElSource source, Object value) {
        if (source.isScript()) {
            return value;
        }
        if (value instanceof String) {
            String str = (String) value;
            int len = str.length();
            StringBuilder builder = new StringBuilder();
            int i = 0;
            for (; i < len; i++) {
                char ch = str.charAt(i);
                if (ch == '\\') {
                    i++;
                    ch = str.charAt(i);
                    switch (ch) {
                        case 'n':
                            builder.append('\n');
                            break;
                        case 'r':
                            builder.append('\r');
                            break;
                        default:
                            builder.append("\\" + ch);
                            break;
                    }
                } else {
                    builder.append(ch);
                }
            }
            return builder.toString();
        }
        return value;
    }
}
